<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.warehouseName"
        clearable
        class="filter-item"
        style="width: 170px;"
        placeholder="输入名称"
      />
      <el-input
        v-model="listQuery.warehouseContacts"
        clearable
        class="filter-item"
        style="width: 170px;"
        placeholder="联系人"
      />
      <el-input
        v-model="listQuery.warehousePhone"
        clearable
        class="filter-item"
        style="width: 170px;"
        placeholder="电话"
      />
      <el-select v-model="listQuery.status" clearable style="width: 170px" class="filter-item" placeholder="请选择状态" >
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.isMain" clearable style="width: 170px" class="filter-item" placeholder="请选择仓库类型" >
        <el-option v-for="(item,index) in isMainMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button
        v-permission="['warehouse:warehouse:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
    </div>
    <div style="padding-bottom: 10px;">
      <el-row>
        <el-col>
          <i class="el-icon-info" style="color:#409EFF;"/><span style="font-size: 14px;color:#409EFF;">主仓库必须只能有一个</span>
        </el-col>
      </el-row>
    </div>
    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="warehouseNo" align="center" label="仓库编号">
        <template slot-scope="scope">
          <el-link :underline="false" type="primary" @click="handleDetail(scope.row)">{{ scope.row.warehouseNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseName" align="center" label="仓库名称"/>
      <el-table-column prop="warehouseContacts" align="center" label="联系人"/>
      <el-table-column prop="warehousePhone" align="center" label="联系电话"/>
      <el-table-column prop="warehouseAddress" align="center" label="联系地址"/>
      <el-table-column align="center" label="仓库类型" prop="isMain">
        <template slot-scope="scope">{{ scope.row.isMain | formatWarehouseType }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.status === 0? '禁用': '正常' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="gmtCreate">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatGmt }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="['warehouse:warehouse:update']"
            v-if="scope.row.status=='1'"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['warehouse:warehouse:active']"
            v-if="scope.row.status=='1' && scope.row.isMain == '0'"
            type="danger"
            size="mini"
            @click=" handleStatus(scope.row)">冻结</el-button>
          <el-button
            v-permission="['warehouse:warehouse:active']"
            v-if="scope.row.status=='0'"
            type="primary"
            size="mini"
            @click="handleStatus(scope.row)"
          >激活</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 详情对话框 -->
    <el-dialog :visible.sync="warehouseDetailVisible" title="详情" @close="resetForm">
      <el-form
        :data="warehouseDetail"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="仓库编号" prop="warehouseNo">
          <el-input v-model="warehouseDetail.warehouseNo" clearable placeholder="" readonly/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="warehouseDetail.warehouseName" clearable placeholder="" readonly/>
        </el-form-item>
        <el-form-item prop="warehouseContacts">
          <label slot="label">联&nbsp;&nbsp;系&nbsp;&nbsp;人</label>
          <el-input v-model="warehouseDetail.warehouseContacts" clearable placeholder="" readonly/>
        </el-form-item>
        <el-form-item label="联系电话" prop="warehousePhone">
          <el-input v-model="warehouseDetail.warehousePhone" clearable placeholder="" readonly/>
        </el-form-item>
        <el-form-item label="联系地址" prop="warehouseAddress" readonly>
          <el-input v-model="warehouseDetail.warehouseAddress" type="textarea" rows="3" clearable placeholder="" readonly/>
        </el-form-item>
        <el-form-item label="详细地址">
          <template>
            <baidu-map
              :center="center"
              :scroll-wheel-zoom="true"
              :map-click="false"
              :zoom="zoom"
              class="map"
              ak="0N3VjpP6QAIojH2rSijad0eIDmpfqs00"
              @click="getClickInfo"
              @ready="initHandler">
              <bm-view class="map"/>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"/>
              <bm-marker :position="markerPos" :dragging="true"/>
              <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location" zoom="12.8" style="display: none" />
            </baidu-map>
          </template>
        </el-form-item>
        <el-form-item label="仓库经纬度">
          <el-row>
            <el-col :span="8">
              <el-input v-model="warehouseDetail.lng" readonly/>
            </el-col>
            <el-col :span="8" :offset="2">
              <el-input v-model="warehouseDetail.lat" readonly/>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="resetForm">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="仓库编号" prop="warehouseNo">
          <el-input v-model="dataForm.warehouseNo" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="dataForm.warehouseName" clearable placeholder=""/>
        </el-form-item>
        <el-form-item prop="isMain">
          <label slot="label">&nbsp;&nbsp;主&nbsp;&nbsp;仓&nbsp;&nbsp;库</label>
          <el-radio v-model="dataForm.isMain" :label="1">是</el-radio>
          <el-radio v-model="dataForm.isMain" :label="0">否</el-radio>
          <el-row>
            <el-col>
              <i class="el-icon-info" style="color:#409EFF;"/><span style="font-size: 14px;color:#409EFF;">主仓库必须只能有一个</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="warehouseContacts">
          <label slot="label">联&nbsp;&nbsp;系&nbsp;&nbsp;人</label>
          <el-input v-model="dataForm.warehouseContacts" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="联系电话" prop="warehousePhone">
          <el-input v-model="dataForm.warehousePhone" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="仓库地址" prop="warehouseAddress">
          <el-row>
            <el-col>
              <el-input
                v-model="dataForm.warehouseAddress"
                clearable
                placeholder="不能超过50个字"
                maxlength="50"
                type="textarea"
                rows="4"
                show-word-limit/>
            </el-col>
            <el-col :span="2"><el-button type="primary" style="margin-top: 10px;" @click="searchOnMap">搜索地图</el-button></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="点击地图获取详细地址">
          <template>
            <baidu-map
              :center="center"
              :scroll-wheel-zoom="true"
              :map-click="false"
              :zoom="zoom"
              class="map"
              ak="0N3VjpP6QAIojH2rSijad0eIDmpfqs00"
              @click="getClickInfo"
              @ready="initHandler">
              <bm-view class="map"/>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"/>
              <bm-marker :position="markerPos" :dragging="true"/>
              <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location" zoom="15" style="display: none" />
            </baidu-map>
          </template>
        </el-form-item>
        <el-form-item label="仓库经纬度">
          <el-row>
            <el-col :span="8">
              <el-input v-model="dataForm.lng" readonly/>
            </el-col>
            <el-col :span="8" :offset="2">
              <el-input v-model="dataForm.lat" readonly/>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.map {
  width: 120%;
  height: 300px;
}
</style>

<script>
import { list, create, del, update, active, detail } from '@/api/warehouse'
import { formatDateAndTime } from '@/filters'
import BaiduMap from 'vue-baidu-map/components/map/Map'
import BmMarker from 'vue-baidu-map/components/overlays/Marker'
import BmView from 'vue-baidu-map/components/map/MapView'
import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch'
import BmInfoWindow from 'vue-baidu-map/components/overlays/InfoWindow'
import BmLabel from 'vue-baidu-map/components/overlays/Label'
import BmNavigation from 'vue-baidu-map/components/controls/Navigation'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const isMainMap = [{ value: 0, name: '辅仓库' }, { value: 1, name: '主仓库' }]
export default {
  name: 'Warehouse',
  components: {
    Pagination,
    BaiduMap,
    BmView,
    BmMarker,
    BmLabel,
    BmLocalSearch,
    BmInfoWindow,
    BmNavigation
  },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTime(time)
    },
    formatWarehouseType(type) {
      return type === 1 ? '主仓库' : '辅仓库'
    }
  },
  data() {
    return {
      isMainMap,
      statusMap: [{ value: 0, name: '禁用' }, { value: 1, name: '正常' }],
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        isMain: undefined
      },
      options: [],
      warehouseDetail: {},
      warehouseDetailVisible: false,
      dataForm: {
        id: undefined,
        warehouseNo: undefined,
        warehouseName: undefined,
        warehouseContacts: undefined,
        warehousePhone: undefined,
        warehouseAddress: undefined,
        status: 1,
        isMain: 0,
        lng: undefined,
        lat: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      keyword: '',
      location: '',
      center: { lng: 0, lat: 0 },
      zoom: 15,
      markerPos: { lng: 0, lat: 0 },
      BMap: null,
      geoCoder: null,
      rules: {
        warehouseNo: [
          { required: true, message: '请输入仓库编号', trigger: 'blur' }
        ],
        warehouseName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        warehouseContacts: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        warehousePhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        warehouseAddress: [
          { required: true, message: '请输入联系地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    searchOnMap() {
      this.$set(this, 'keyword', this.dataForm.warehouseAddress)
    },
    initHandler(e) {
      if (e.BMap) {
        this.BMap = e.BMap
        this.geoCoder = new this.BMap.Geocoder()
      }
      if (this.dataForm.lat && this.dataForm.lng) {
        this.center.lng = this.dataForm.lng * 1
        this.center.lat = this.dataForm.lat * 1
        this.zoom = 15
        this.markerPos.lng = this.dataForm.lng * 1
        this.markerPos.lat = this.dataForm.lat * 1
      } else {
        this.center.lng = 116.404
        this.center.lat = 39.915
        this.zoom = 15
        this.markerPos.lng = 116.404
        this.markerPos.lat = 39.915
      }
      if (this.dataForm.warehouseAddress) {
        this.$set(this, 'keyword', this.dataForm.warehouseAddress)
      }
    },
    getClickInfo(e) {
      this.markerPos.lng = e.point.lng
      this.markerPos.lat = e.point.lat
      this.dataForm.lng = this.markerPos.lng
      this.dataForm.lat = this.markerPos.lat
      if (this.BMap) {
        this.geoCoder.getLocation(e.point, (res) => {
          const addrComponent = res.addressComponents
          const surroundingPois = res.surroundingPois
          const province = addrComponent.province
          const city = addrComponent.city
          const district = addrComponent.district
          let addr = addrComponent.street
          if (surroundingPois.length > 0 && surroundingPois[0].title) {
            if (addr) {
              addr += `-${surroundingPois[0].title}`
            } else {
              addr += `${surroundingPois[0].title}`
            }
          } else {
            addr += addrComponent.streetNumber
          }
          const site = province + '' + city + '' + district + '' + addr
          this.$set(this.dataForm, 'warehouseAddress', site)
        })
      }
    },
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        isMain: 0,
        lat: undefined,
        lng: undefined
      }
      this.$set(this, 'keyword', '')
      this.location = ''
      this.center = { lng: 0, lat: 0 }
      this.zoom = 15
      this.markerPos = { lng: 0, lat: 0 }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          create(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.center.lng = row.lng * 1
      this.center.lat = row.lat * 1
      this.zoom = 15
      this.markerPos.lng = row.lng * 1
      this.markerPos.lat = row.lat * 1
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.lng && this.dataForm.lat) {
            update(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          } else {
            this.$notify.error({
              title: '失败',
              message: '经纬度有误'
            })
          }
        }
      })
    },
    handleDetail(row) {
      detail(row).then(response => {
        this.warehouseDetail = response.data.data
        this.dataForm = response.data.data
        this.center.lng = this.warehouseDetail.lng * 1
        this.center.lat = this.warehouseDetail.lat * 1
        this.zoom = 15
        this.markerPos.lng = this.warehouseDetail.lng * 1
        this.markerPos.lat = this.warehouseDetail.lat * 1
      })
      this.warehouseDetailVisible = true
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    }
  }
}
</script>
